from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

# 假设这是你的火山方舟API密钥
ARK_API_KEY = '21f51f6d-23fc-40e2-8807-84bc65ce3db8'
VOLCANO_CHAT_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"

def chat_with_volcano(param):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {ARK_API_KEY}'
    }
    response = requests.post(VOLCANO_CHAT_URL, json=param, headers=headers)

    if response.status_code == 200:
        result = response.json()
        # 根据火山方舟API响应格式解析，通常在choices[0].message.content中
        content = result['choices'][0]['message']['content']
        return content if content else ''
    else:
        raise Exception(f"请求火山方舟API失败, status code: {response.status_code}, response: {response.text}")

def chat(text,role_desc):
    if not text or not text.strip():
        return jsonify({'error': '问题不能为空'}), 400

    volcano_chat_param = {
        'model': 'deepseek-v3-250324',
        'messages': [
            {'role': 'user', 'content': text},
            {'role': 'system', 'content': role_desc if role_desc is not None else '你是一个万能的助手，请回答问题'}
        ]
    }

    try:
        response_content = chat_with_volcano(volcano_chat_param)
        return response_content
    except Exception as e:
        return f'服务器出错:{e}'


